<?php

App::uses('Folder', 'Utility');
App::uses('File', 'Utility');

/**
 * Description of ClearCacheTask
 *
 * @author jarrod
 */
class ClearCacheTask extends Shell {
    private $exclude = array('.svn','.htaccess');
    
    public function execute($path=null) {
        if(strpos($path, '..') !== false){
            $this->out('<error>You must not use ".." in path</error>');
            return;
        }
        if(substr($path, 0, 1) !== '/'){
            $path = CACHE . $path;
        }
        if(!is_dir($path)){
            $this->out('<error>The directory ' . $path . ' is not exists..</error>');
            return;
        }
        $this->out('Clear task: Cleaning ' . $path . '...');
        $this->delete($path);
        
    }
    
    
    private function delete($path){
        
        if(is_file($path)){
            foreach ($this->exclude as $exclude){
                if(strpos($path, $exclude) !== false){
                    return;
                }
            }
            if(!unlink($path)){
                $this->log('Unable delete file: ' . $path, 'error');
                $this->out('<warning>Unable delete directory: ' . $path . '.</warning>');
            }
            $this->out('Remove file: ' . $path);
            return;
        }
        
        $folder = new Folder($path, true);
        $contents = $folder->read(false, $this->exclude, true);
        $folders = $contents[0];
        $files = $contents[1];

        foreach ($folders as $_folder) {
            $handler = new Folder($_folder, true);
            if (!$handler->delete()) {
                $this->log('Unable delete directory: ' . $_folder, 'error');
                $this->out('<warning>Unable delete directory: ' . $_folder . '.</warning>');
            } else {
                $this->out('Remove directory: ' . $_folder);
            }
        }

        foreach ($files as $file) {
            $this->delete($file);
        }
        
    }
    
}

?>
